package com.jky.trial.common;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by suweiming on 2017/12/20.
 */

public class Utils {
    private static final int DEF_DIV_SCALE = 5;

    /**
     * 文件下载时文件名称
     *
     * @Title: processFileName http://blog.csdn.net/heyanfeng22/article/details/49453405
     * @Description: ie, chrom, firfox下处理文件名显示乱码
     * @ref http://blog.csdn.net/qq_16091839/article/details/72923970
     */
    public static String processFileName(HttpServletRequest request, String fileNames) {
        String codedfilename = null;
        try {
            String agent = request.getHeader("USER-AGENT");
            if (null != agent && -1 != agent.indexOf("MSIE") || null != agent
                    && -1 != agent.indexOf("Trident") || null != agent && -1 != agent.toLowerCase().indexOf("like gecko")) {// ie
                String name = java.net.URLEncoder.encode(fileNames, "UTF8");
                codedfilename = name;
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等
                codedfilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return codedfilename;
    }

    /***
     * 返回某一日期串之前的日期字符串
     * @param date 某一具体日期字符串
     * @return
     * ref : http://blog.csdn.net/u014099894/article/details/51089182
     */
    public static String getYesterdayDate(String date) {

        //解析指定Date
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        Date parseDate = null;
        try {
            parseDate = simpleDateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //设置Calendar
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(parseDate);

        /*
         * 核心代码，回滚到前一天。
         */
        //backOne(calendar);//错误
        backTwo(calendar);//正确

        //转换格式
        String format = simpleDateFormat.format(calendar.getTime());

        System.out.println(format);
        return format;
    }

    //使用roll()方法回滚
    private static void backOne(Calendar calendar) {
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
    }

    //使用set()方法回滚
    private static void backTwo(Calendar calendar) {
        int day = calendar.get(Calendar.DATE);
        calendar.set(Calendar.DATE, day - 1);
    }


    /**
     * 税额
     *
     * @param taxRatio 税率
     * @param total    价税合计金额
     * @return
     */
    public static BigDecimal taxTotal(BigDecimal taxRatio, BigDecimal total) {
        return total.divide(taxRatio.add(BigDecimal.valueOf(1.0)), 2); // 增加精度，防止无限循环
    }

    /**
     * list 转化为 Map
     *
     * @param list
     * @param c    指定要调用方法对应的类
     * @param key  指定字段key,多个字段使用逗号','分隔
     * @return
     * @ref http://jackyrong.iteye.com/blog/2158009
     */
    public static Map<String, Object> convertListToMap(List list, Class<?> c, String key) {
        Map<String, Object> maps = new HashMap<String, Object>();
        Class[] argsClass = new Class[0];
        Object[] args = new Object[0];
        String[] keys = key.split(",");
        System.out.println(String.valueOf(keys) + "--------");
        for (Object obj : list) {
            Method method = null;//
//            Method method1 = Method.;//
            Class class_ = c != null ? c : obj.getClass();
            String keyTemp = "";
            for (String keyStr : keys) {
                try {
                    method = class_.getMethod("get" + keyStr.substring(0, 1).toUpperCase() + keyStr.substring(1), argsClass);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
                try {
                    keyTemp += (String) method.invoke(obj, args);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            maps.put(keyTemp, obj);
        }
        return maps;
    }


    /**
     * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址;
     *
     * @param request
     * @return
     */
    public final static String getIp(HttpServletRequest request) {
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址
        return request.getHeader("X-Forwarded-For");
    }

    /**
     * URL编码（utf-8）
     *
     * @param source
     * @return
     */
    public static String urlEncodeUTF8(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取随机字符串
     *
     * @return
     */
    public static String getNonceStr() {
        return UUID.randomUUID().toString();
    }

    /***
     *  获取秒数
     * @return
     */
    public static String getSec() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    public static void main(String[] arg) {
        System.out.println(getSec());
    }

}
